const fs = require('fs')
const { exec } = require('child_process')
const { resolve, join } = require('path')
const minimist = require('minimist')

const args = minimist(process.argv.slice(2))

const rootPath = join(__dirname, '..')

const userOptions = {
  logo: args.logo === 'yes',
  package: args.package.split(','),
  platform: args.platform
}

console.log('读取脚本参数中 🤬')

console.log(userOptions.logo ? '去掉logo...' : '保留logo...')

console.log('打包' + userOptions.package + '等模块中')

console.log('打包至' + userOptions.platform + '平台')

const AppConfigFs = fs.readFileSync(resolve(rootPath, 'config/defaultSetting.ts'), 'utf8')

if (userOptions.logo) {
  const AppConfigFsr =
`export default {
  appName: '',
  userInfoHidden: true,
  documentIco: '',
  logoExpand: '',
  logoContract: '',
  logout: ''
}
`

  console.log('写入地址：', resolve(rootPath, 'config/defaultSetting.ts'))
  fs.writeFileSync(resolve(rootPath, 'config/defaultSetting.ts'), AppConfigFsr, 'utf-8')
}

const file = fs.readFileSync(resolve(rootPath, 'src/router/index.ts'), 'utf8')

const r = file.replace(
  'const _routes = [iot, schedule, view, lowcode, user, login]',
  `const _routes = ${userOptions.package}`
)

fs.writeFileSync(resolve(rootPath, 'src/router/index.ts'), r, 'utf-8')

console.log('修改路由值成功 🌹')
console.log('开始打包  📦')
console.log('打包中...... 💪')

if (userOptions.platform === 'web') {
  exec('npm run build', (error, stdout, stderr) => {
    if (error) {
      console.error(`执行脚本时出错：${error}`)
      fs.writeFileSync(resolve(rootPath, 'src/router/index.ts'), file, 'utf-8')
      userOptions.logo && fs.writeFileSync(resolve(rootPath, 'config/defaultSetting.ts'), AppConfigFs, 'utf-8')
    } else {
      console.log('打包成功 🎉')
      fs.writeFileSync(resolve(rootPath, 'src/router/index.ts'), file, 'utf-8')
      userOptions.logo && fs.writeFileSync(resolve(rootPath, 'config/defaultSetting.ts'), AppConfigFs, 'utf-8')
    }
  })
} else {
  exec(`electron . ${userOptions.platform}`)
}
